﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Common;
using System.Data.Services.Client;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;
using Microsoft.WindowsAzure.StorageClient.Tasks;
using System.Xml.Serialization;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Diagnostics;
using System.Diagnostics;

namespace DDMySqlBackupRestore
{
    [Serializable]
   
   public class RestoreTrackingTable : TableServiceEntity
    { 
        
        public const string TABLE_NAME = "ddrestoretrackingtable";

       
        /// <summary>
        /// DeplopymentId_RoleId
        /// </summary>
//public override string PartitionKey
//{
//  get { return SecUtility.PartitionAndRowKeyEscape(base.PartitionKey); }
//  set { base.PartitionKey = SecUtility.PartitionAndRowKeyEscape(value);}
//}
// To sort the time from newest to oldest
// <DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks>_EntityType
// The ticks can be at most 19 digits
public static string CreateRowKey(string databaseName)
{
    return string.Format("{0}_{1}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks, databaseName);

}

public static string CreatePartitionKey(string deploymentId, string roleId, string instanceId)
{
    return string.Format("{0}_{1}_{2}", deploymentId, roleId, instanceId);

}
    


     public string BackupFileContainerName {get;set;}
        public string BackupFileBlobName {get;set;}
       
        public DateTime DateRestored {get;set;}
        public string StatusMessage { get; set; }
        public int Status { get; set; }
        public bool CreatedDb { get; set; }
        public string CreateDbStatus { get; set; }
        public RestoreTrackingTable()
        {


        }

      

    }

    public static class RestoreTrackingTableUtil
    {
        public static readonly TableStorageHelper TableHelper;


        static RestoreTrackingTableUtil()
        {
            try
            {
                string storageAccountConnectionString = Program.GetConfigValueAsString("com.dynamicdeploy.backuprestore.mysql.DataConnectionString");
                TableHelper = new TableStorageHelper(storageAccountConnectionString);

                //Create only if table did not exist
                if (TableHelper.CreateTable(RestoreTrackingTable.TABLE_NAME))
                {
                    Trace.TraceInformation("Created Table " + RestoreTrackingTable.TABLE_NAME);


                }
                else
                {
                    Trace.TraceInformation("Could not create Table. May be already exists. " + RestoreTrackingTable.TABLE_NAME);

                }



            }
            catch (Exception ex)
            {

                Trace.TraceError("RestoreTrackingTable Init " + ex.Message);
            }

        }
        public static IQueryable<RestoreTrackingTable> GetLatestRestores(string deploymentId, string roleId, string instanceId, string databaseName, int count)
        {
            string partitionKey = RestoreTrackingTable.CreatePartitionKey(deploymentId, roleId, instanceId);
          
           
            string startRowKey = string.Format("{0:D19}_{1}", DateTime.MinValue.Ticks, databaseName);
            string endRowKey = string.Format("{0:D19}_{1}", DateTime.MaxValue.Ticks, databaseName);
            TableServiceContext tableServiceContext = TableHelper.TableClient.GetDataServiceContext();
            tableServiceContext.IgnoreResourceNotFoundException = true;

            return
                (from entity in
                     tableServiceContext.CreateQuery<RestoreTrackingTable>(RestoreTrackingTable.TABLE_NAME)
                 where entity.PartitionKey == SecUtility.PartitionAndRowKeyEscape(partitionKey) && entity.RowKey.CompareTo(startRowKey) >= 0
                    && entity.RowKey.CompareTo(endRowKey) <= 0
                 select entity).Take(count);


        }

        public static bool SaveRestoreTracking(RestoreTrackingTable item)
        {
           
            return TableHelper.UpsertEntity(RestoreTrackingTable.TABLE_NAME, item);

        }
     
    }
}
